package com.jinyu.admin.controller.sys;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.jinyu.admin.service.sys.SysUserService;
import com.jinyu.common.base.ApiRestResponse;
import com.jinyu.dao.entity.sys.SysUser;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @Author: yangli
 * @Despriction:    用户模块
 * @Package: com.jinyu.admin.controller.sys
 * @Date:Created in 2022/5/3 22:27
 * @Modify By:
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    /**
     *  新增用户接口
     * @param sysUser   用户信息
     * @return  ApiRestResponse
     */
    @PostMapping("/add/1.0")
    public ApiRestResponse<Object> addUser (@RequestBody @Valid SysUser sysUser) {
        log.info("用户信息{}",sysUser.toString());
        int insert = sysUserService.insert(sysUser);
        return insert > 0 ? ApiRestResponse.ok("新增用户成功") : ApiRestResponse.err("新增用户失败");
    }

    /**
     *  根据用户编码获取用户信息
     * @param userCode  用户编码
     * @return
     */
    @GetMapping("/selectByOne/1.0")
    public ApiRestResponse<Object> selectByOne (@RequestParam("userCode") String userCode) {
        SysUser sysUser = sysUserService.selectByOne(userCode);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return !Objects.isNull(sysUser) ? ApiRestResponse.ok("获取用户成功",sysUser) : ApiRestResponse.err("获取用户失败");
    }

    /**
     *  获取当前用户的信息
     * @return  ApiRestResponse
     */
    @GetMapping("/getCurrentUserInfo/1.0")
    public ApiRestResponse<Object> getCurrentUserInfo () {
        //如果当前会话未登录，这句代码会抛出 `NotLoginException` 异常
        StpUtil.checkLogin();
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        //获取当前用户的user-session
        SaSession userSession = StpUtil.getSession();
        SysUser sysUser = userSession.getModel("userModel:" + tokenInfo.getLoginId() + ":", SysUser.class);
        return !Objects.isNull(sysUser) ? ApiRestResponse.ok("获取用户成功",sysUser) : ApiRestResponse.err("获取用户失败");
    }

}
